using System;
using System.Globalization;
using System.Windows.Forms;

using FreeFlow.Client;

namespace FreeFlow.WinFormsControls
{
	/// <summary>
	/// A date time control.
	/// </summary>
	public class DateTimeControl : DateTimePicker, IFillable, IRefillable
	{
    #region IFillable Members

    /// <summary>
    /// Renders the date-time control with static layout information using the specified field.
    /// </summary>
    /// <param name="field">Field.</param>
    public void Render(FreeFlow.Client.Field field)
    {
      DateTimeField dateField = (DateTimeField)field;
      if (dateField.DateTimeType == DateTimeType.Time)
        Format = DateTimePickerFormat.Time;
      else if (dateField.DateTimeType == DateTimeType.Date)
        Format = DateTimePickerFormat.Short;
      else if (dateField.DateTimeType == DateTimeType.DateTime)
      {
        Format = DateTimePickerFormat.Custom;
        CustomFormat = 
          CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " +
          CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern; 
      }
    }

    private DateTime initialValue;
    /// <summary>
    /// Fills the date-time control with values from the specified field.
    /// </summary>
    /// <param name="field">Field.</param>
    public void Fill(FreeFlow.Client.Field field)
    {
      DateTimeField dateTimeField = (DateTimeField)field;
            
      ShowCheckBox = true;
      if (dateTimeField.DateTime == Constants.NullDateTime)
        Checked = false;
      else
        Value = dateTimeField.DateTime;
      initialValue = dateTimeField.DateTime;
    }

    /// <summary>
    /// Fills the field from the control.
    /// </summary>
    /// <param name="field">Field.</param>
    public void FillField(Field field)
    {
      DateTimeField dateField = (DateTimeField)field;
      if (!Checked)
        dateField.DateTime = Constants.NullDateTime;
      else
        dateField.DateTime = Value;
    }

    #endregion
    #region IRefillable Members

    /// <summary>
    /// Event triggered when a refill should occur
    /// </summary>
    public event System.EventHandler Refill;

    /// <summary>
    /// Triggers a refill.
    /// </summary>
    /// <param name="e">E.</param>
    protected override void OnLeave(EventArgs e)
    {
      base.OnLeave(e);
      if (Value != initialValue)
        if (Refill != null)
          Refill(this, e);
    }

    #endregion
  }
}
